//
//  VRAddressBookViewController.m
//  VRDoctor
//
//  Created by Veer on 16/5/27.
//
//

#import "VRAddressBookViewController.h"
#import <AddressBook/AddressBook.h>

#import "NSString+Tools.h"
#import "VRAddressBookCell.h"
#import "VRAddressBookModel.h"
#import "VRAddressBookTool.h"

@interface VRAddressBookViewController ()

@property (nonatomic, strong) NSMutableArray *contactArray;

@property (nonatomic, assign) NSInteger selectedCount;//右上角的数字

@property (nonatomic, strong) NSArray *sectionArray;//row arr
@property (nonatomic, strong) NSArray *sectionTitleArray;//section arr
@property (nonatomic, strong) NSMutableArray *searchResultArr;

// 是否执行过搜索
@property (nonatomic, assign) BOOL isSearched;

@end

@implementation VRAddressBookViewController


- (void)setSelectedCount:(NSInteger)selectedCount
{
    _selectedCount = selectedCount;
    
    // 设置右上角数组
    
    NSString *rightTitle = @"导入";
    if (selectedCount != 0) {
        rightTitle = [NSString stringWithFormat:@"导入(%ld)", selectedCount];
    }
    UIButton *rightBtn = self.navigationItem.rightBarButtonItem.customView;
    [rightBtn setTitle:rightTitle forState:UIControlStateNormal];
}


- (NSMutableArray *)contactArray
{
    if (nil == _contactArray) {
        _contactArray = [NSMutableArray array];
    }
    return _contactArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"添加患者";
    
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexColor = [UIColor darkGrayColor];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setupNav];
    [self requestAuth];
    
    VRLog(@"test:%@", @"沈红2".pinyin);
}


- (void)setupNav
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:@"导入" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    
    button.frame = (CGRect){{0, 0}, CGSizeMake(70, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(onImportBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


/**
 *  请求授权
 */
- (void)requestAuth
{
    //如果用户没决定过，请求授权
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        //创建通讯录
        ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
        //请求授权
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            if (granted) {//请求授权页面用户同意授权
                //读取通讯录人员数量,此处不可使用上面请求授权的通讯录对象,会崩溃
                ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
                //获取联系人数量
//                CFIndex personCount = ABAddressBookGetPersonCount(addressBook);
                [self getContacts];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //xxx
                });
                CFRelease(addressBook);
            }
            CFRelease(addressBookRef);
        });
            //如果是已授权状态
    } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
        //创建通讯录
        //读取通讯录人员数量
        ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
//        CFIndex personCount = ABAddressBookGetPersonCount(addressBookRef);
        [self getContacts];
        CFRelease(addressBookRef);
    } else {
//        [self showAlertWithTitle:@"提醒" message:@"请在设置中打开通讯录授权"];
    }
}


/**
 *  获取通讯录数据
 */
- (void)getContacts
{
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        //拿到所有联系人
        CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
        //数组数量
        CFIndex peopleCount = CFArrayGetCount(peopleArray);
        for (int i = 0; i < peopleCount; i++) {
            //拿到一个人
            ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
            //拿到姓名
            //姓
            NSString *lastNameValue = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
            //名
            NSString *firstNameValue = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
            
            //公司名kABPersonOrganizationProperty
            NSString *organizationNameValue = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonOrganizationProperty);
            
            //拿到多值电话
            ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
            //多值数量
            CFIndex phoneCount = ABMultiValueGetCount(phones);
            
            NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, 0);
            
            firstNameValue = firstNameValue == nil ? @"": firstNameValue;
            lastNameValue = lastNameValue == nil ? @"": lastNameValue;
            NSString *nameStr = [NSString stringWithFormat:@"%@%@", firstNameValue, lastNameValue];
            if (nameStr.length == 0) {
                organizationNameValue = organizationNameValue == nil ? @"": organizationNameValue;
                nameStr = organizationNameValue;
            }
            VRLog(@"%@:%@", nameStr, phoneValue);
            
            VRAddressBookModel *model = [[VRAddressBookModel alloc] init];
            model.name = nameStr;
            model.phoneNumber = phoneValue;
            [self.contactArray addObject:model];
            
            //        for (int j = 0; j < phoneCount ; j++) {
            //            //电话标签本地化(例如是住宅,工作等)
            //            NSString *phoneLabel = (__bridge_transfer NSString *)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phones, j));
            //            //拿到标签下对应的电话号码
            //            NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, j);
            //
            //            NSString *nameStr = [NSString stringWithFormat:@"%@%@", firstNameValue, lastNameValue];
            //
            //            VRLog(@"%@:%@", nameStr, phoneValue);
            //        }
            CFRelease(phones);
        }
        
        CFRelease(addressBook);
        CFRelease(peopleArray);
        
        
        _sectionArray = [VRAddressBookTool getFriendListDataBy:self.contactArray];
        
        _sectionTitleArray = [VRAddressBookTool getFriendListSectionBy:[_sectionArray mutableCopy]];
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [self.tableView reloadData];
        });
        
    });
    
    
    
}


#pragma mark - 点击事件
- (void)onImportBtnClick:(UIButton *)sender
{
    [SVProgressHUD showImage:nil status:@"\n\n 暂未开放此功能    \n\n"];
}


#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionArray.count;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.isSearched) {
        return 0;
    }
    return 22.0;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //viewforHeader
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:VRFont(14.5)];
        
        [label setTextColor:[UIColor grayColor]];
        [label setBackgroundColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1]];
    }
    
    [label setText:[NSString stringWithFormat:@"  %@",self.sectionTitleArray[section + 1]]];
    
    return label;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.isSearched) {
        return nil;
    }else{
        return self.sectionTitleArray;
        
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index - 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.sectionArray[section] count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VRAddressBookModel *model = self.sectionArray[indexPath.section][indexPath.row];
    
    VRAddressBookCell *cell = [VRAddressBookCell cellWith:tableView];
    cell.model = model;
    
    if (indexPath.row < [self.sectionArray[indexPath.section] count] - 1) {
        cell.lineType = LineTypeCenter;
    }else{
        cell.lineType = LineTypeNone;
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    VRAddressBookModel *model = nil;
    if (self.isSearched) {
        model = self.searchResultArr[indexPath.row];
    }else{
        model = self.sectionArray[indexPath.section][indexPath.row];
    }
    
    model.isSelected = !model.isSelected;
    
    VRAddressBookCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelected = model.isSelected;
    
    if (model.isSelected) {
        self.selectedCount++;
    }else{
        self.selectedCount--;
    }
}

@end
